package lesson.grade;

import lesson.db.DbUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class GradeService {


    /**
     * 添加用户
     * @param name
     * @param id
     */
    public String saveGrade(String name, Integer id) {


        if (checkExist(id,name)){
            return "该名称已被注册";
        }
        if(id==null){
            SqlSession session = DbUtil.getSession(true);
            try{
                GradeDao gradeDao = session.getMapper(GradeDao.class);
                gradeDao.addGrade(name);

            }finally {

                session.close();
            }
        }else{
            SqlSession session = DbUtil.getSession(true);
            try{
                GradeDao gradeDao = session.getMapper(GradeDao.class);
                gradeDao.updateGrade(name,id);

            }finally {

                session.close();
            }

        }
        return null;

    }


    /**
     * 检测叫这个名字的用户是否存在
     * @param name
     * @return
     */
    public boolean checkExist(Integer exceptId,String name) {
        SqlSession session = DbUtil.getSession(true);
        try{
            GradeDao gradeDao = session.getMapper(GradeDao.class);
            boolean exist = gradeDao.checkExist(exceptId,name);
            return exist;

        }finally {
            session.close();

        }
    }
    public List<Grade> list(String keywords){
        SqlSession session = DbUtil.getSession(true);
        try{
            GradeDao gradeDao = session.getMapper(GradeDao.class);
            List<Grade> list = gradeDao.list(keywords);
            return list;

        }finally {
            session.close();

        }
    }



    public String del(Integer id) {
        SqlSession session = DbUtil.getSession(true);
        try{
            GradeDao gradeDao = session.getMapper(GradeDao.class);
            gradeDao.delGrade(id);

        }finally {

            session.close();
        }
        return null;
    }
    public Grade getById(Integer id){
        SqlSession session = DbUtil.getSession(true);
        try{
            GradeDao gradeDao = session.getMapper(GradeDao.class);
            Grade grade =gradeDao.getById(id);
            return grade;

        }finally {
            session.close();

        }
    }
}
